// pages/myself/edit-awards/editAwards.js
const app = getApp()
const { validate } = require('../../../utils/validator.js')
const validator = (rule, value, callback) => {
  const reg = /^[a-zA-Z\u4e00-\u9fa50-9《》，,"“]*$/
  if (!reg.test(value)) {
    callback(new Error(`中文或英文或数字或书名号或逗号或双引号`))
  } else {
    callback()
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    type: '',
    userId: '',
    list: [],
    titles: {
      certificate: '获奖证书或贡献',
      awards: '获奖奖项或荣誉',
    },
    rules: {
      certificate: [
        {
          type: 'array',
          defaultField:  {
            type: 'object',
            fields: {
              content: [
                { validator }
              ]
            }
          }
        },
      ],
      awards: [
        {
          type: 'array',
          defaultField:  {
            type: 'object',
            fields: {
              content: [
                { validator }
              ]
            }
          }
        },
      ]
    },
    loading: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    const title = this.data.titles[options.type]
    this.setData({
      type: options.type,
      list: JSON.parse(decodeURIComponent(options.value)),
      userId: options.id,
      title
    })
    console.log(JSON.parse(decodeURIComponent(options.value)))
    wx.setNavigationBarTitle({
      title: `修改${title}`
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  add: function () {
    const { list, type, userId } = this.data
    this.setData({
      [`list[${list.length}]`]: {
        content: '',
        type,
        userId
      }
    })
  },
  del: function (e) {
    let { index } = e.currentTarget.dataset;
    let list = this.data.list
    list.splice(index, 1)
    this.setData({
      list
    })
  },
  inputInfo: function (e) {
    let dataset = e.currentTarget.dataset;
    let value = e.detail.value;
    this.setData({
      [`list[${dataset.index}].content`]: value
    })
  },
  edit: function (e) {
    const { type, rules, list } = this.data
    validate(type, rules[type], list, (valid) => {
      if (valid) {
        this.setData({
          loading: true
        })
        app.api.post({
          url: 'cpic_user_updateUserExtInfo',
          data: {type, list}
        }).then(res => {
          wx.navigateBack()
        }).finally(() => {
          this.setData({
            loading: false
          })
        })
      }
    })
  },
})